import { ComponentProps } from "react"
import { RepeatMode } from "react-native-track-player"
import { match } from "ts-pattern"
import { MaterialCommunityIcons } from '@expo/vector-icons';
import { colors } from "@/constants/tokens";
import { useTrackPlayerRepeatMode } from "@/hooks/useTrackPlayerRepeatMode";
const repeatOrder = [
    RepeatMode.Off,
    RepeatMode.Queue,
    RepeatMode.Track,
] as const

type IconProps = Omit<ComponentProps<typeof MaterialCommunityIcons>,'name'>
type IconName = ComponentProps<typeof MaterialCommunityIcons>['name']

export const PlayerRepeatToggle = ({...iconProps}:IconProps) => {
    
    const { repeatMode,changeRepeatMode } = useTrackPlayerRepeatMode()
    const icon = match(repeatMode)
    .returnType<IconName>()
    .with(RepeatMode.Off, () => 'repeat-off')
    .with(RepeatMode.Track, () => 'repeat-once')
    .with(RepeatMode.Queue, () => 'repeat')
    .otherwise(() => 'repeat-off')

    const toogeRepeatMode = () => {
        if(repeatMode == null) return;
        const currenIndex = repeatOrder.indexOf(repeatMode)
        const nextIndex = (currenIndex + 1) % repeatOrder.length;
        const newRepeatMode = repeatOrder[nextIndex];
        changeRepeatMode(newRepeatMode);
    } 

    return <MaterialCommunityIcons name={icon}  onPress={toogeRepeatMode} color={colors.icon} {...iconProps} />
    
}